package www.ld.com.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import www.ld.com.dictionary.UseStatusEnum;
import www.ld.com.domain.post.pojo.PostPO;
import www.ld.com.domain.post.query.PostQuery;
import www.ld.com.exception.ValidateException;
import www.ld.com.mapper.PostMapper;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PostService {
    @Resource
    private PostMapper postMapper;

    public Page<PostPO> pagePostByPostQuery(PostQuery postQuery) {
        return postMapper.selectPage(
                new Page<PostPO>(postQuery.getCurrent(), postQuery.getSize()),
                new LambdaQueryWrapper<PostPO>()
                        .select(PostPO::getId, PostPO::getCode, PostPO::getName, PostPO::getStatus, PostPO::getSort)
                        .like(StrUtil.isNotBlank(postQuery.getName()), PostPO::getName, postQuery.getName())
                        .like(StrUtil.isNotBlank(postQuery.getCode()), PostPO::getCode, postQuery.getCode())
                        .eq(postQuery.getStatus() != null, PostPO::getStatus, postQuery.getStatus())
                        .orderByAsc(PostPO::getSort)
        );
    }

    @Transactional
    public void savePostPO(PostPO postPO) {

        postMapper.insert(postPO);
    }

    @Transactional
    public void updatePostPOById(PostPO postPO) {
        if (postPO.getStatus() == UseStatusEnum.STOP_USING && postMapper.existPost(String.valueOf(postPO.getId()))) {
            throw new ValidateException("修改失败：该岗位有用户使用,岗位状态不能改为“停用”");
        }
        postMapper.updateById(postPO);
    }


    public PostPO getPostPOById(String id) {
        return postMapper.selectById(id);
    }

    public void deletePostById(String id) {
        if (postMapper.existPost(id))
            throw new ValidateException("删除失败：该岗位有用户使用");
        postMapper.deleteById(id);
    }

    public List<PostPO> findPostPO() {
        return postMapper.selectList(new LambdaQueryWrapper<PostPO>()
                .select(PostPO::getName, PostPO::getId, PostPO::getStatus)
        );
    }


}
